<?php

declare(strict_types=1);

namespace app\xapply\controller;

use think\facade\Db;
use app\xapply\middleware\Auth;

class Login
{

    /**
     * 登录接口
     * url: http://域名/xapply/login
     * doc: http://lutui.net/doc/app/login.html
     */
    public function index()
    {
        $param = get_params();
        $user = Db::name('Admin')->where(['mobile' => $param['username']])->find();
        if (empty($user)) {
            return json(['error' => '帐号或密码错误']);
        }
        $param['pwd'] = set_password($param['password'], $user['salt']);
        if ($param['pwd'] !== $user['pwd']) {
            return json(['error' => '帐号或密码错误']);
        }
        if ($user['status'] == -1) {
            return json(['error' => '该用户禁止登录']);
        }
        $data = [
            'last_login_time' => time(),
            'last_login_ip' => request()->ip(),
            'login_num' => $user['login_num'] + 1,
        ];
        Db::name('Admin')->where(['id' => $user['id']])->update($data);
        $token = make_token().'-'.get_codeno('xapply-').'-'.set_salt();
        Auth::update([
            'user_id' => $user['id'],
            'token' => $token,
            'push' => $param['pushToken'],
            'lang' => $param['lang'],
            'device' => $param['device'],
        ]);
        return json(['error' => '', 'token' => $token]);
    }
}
